<?php
/*
本系统由苏酷伊基于SiteHub项目二次开发
作者博客： https://www.sukuy.com/
后续更新地址： https://www.sukuy.com/navigation
作者QQ：3288637559
QQ交流群：884250547
任何第三方非官网在发布本系统时，不得删除该注释、版权信息、作者信息及官网等内容
*/
define('IN_ADMIN', true);
require('../includes/common.php');
if (defined('FROM_RESETPWD') || defined('FROM_API_APPLY')) {
    return;
}
function get_email_smtp_template($email) {
    $domain = explode('@', $email)[1];
    $templates = array(
        
        'qq.com' => array(
            'server' => 'smtp.qq.com',
            'port' => 465,
            'ssl' => 1,
            'note' => 'QQ邮箱需开启SMTP服务并使用授权码登录'
        ),
        
        '163.com' => array(
            'server' => 'smtp.163.com',
            'port' => 465,
            'ssl' => 1,
            'note' => '网易邮箱需开启SMTP服务并使用授权码登录'
        ),
        
        '126.com' => array(
            'server' => 'smtp.126.com',
            'port' => 465,
            'ssl' => 1,
            'note' => '网易邮箱需开启SMTP服务并使用授权码登录'
        ),
        
        'yeah.net' => array(
            'server' => 'smtp.yeah.net',
            'port' => 465,
            'ssl' => 1,
            'note' => '网易邮箱需开启SMTP服务并使用授权码登录'
        ),
        
        'aliyun.com' => array(
            'server' => 'smtp.aliyun.com',
            'port' => 465,
            'ssl' => 1,
            'note' => '阿里企业邮箱SMTP配置'
        ),
        'aliyun-inc.com' => array(
            'server' => 'smtp.qiye.aliyun.com',
            'port' => 465,
            'ssl' => 1,
            'note' => '阿里企业邮箱SMTP配置'
        ),
        
        'gmail.com' => array(
            'server' => 'smtp.gmail.com',
            'port' => 587,
            'ssl' => 1,
            'note' => 'Gmail需开启SMTP服务并可能需要应用专用密码'
        ),
        
        'outlook.com' => array(
            'server' => 'smtp.office365.com',
            'port' => 587,
            'ssl' => 1,
            'note' => 'Outlook邮箱SMTP配置'
        ),
        'hotmail.com' => array(
            'server' => 'smtp.office365.com',
            'port' => 587,
            'ssl' => 1,
            'note' => 'Hotmail邮箱SMTP配置'
        )
    );
    
    
    foreach ($templates as $key => $template) {
        if (strpos($domain, $key) !== false) {
            return $template;
        }
    }
    
    return false;
}


function send_email($to, $subject, $message, $options = array()) {
    global $conf;
    
    
    if(empty($conf['smtp_server']) || empty($conf['smtp_port']) || empty($conf['smtp_user']) || empty($conf['smtp_pass']) || empty($conf['smtp_from'])) {
        $error_msg = '邮件服务器配置不完整';
        add_email_log($to, $subject, 0, $error_msg);
        return $error_msg;
    }
    
    
    if(!filter_var($to, FILTER_VALIDATE_EMAIL)) {
        $error_msg = '收件人邮箱格式不正确';
        add_email_log($to, $subject, 0, $error_msg);
        return $error_msg;
    }
    
    
    if (empty($subject)) {
        
        $plain_text = strip_tags($message);
        
        $plain_text = preg_replace('/\s+/', ' ', $plain_text);
        
        $subject = mb_substr(trim($plain_text), 0, 50, 'UTF-8');
        
        if (empty($subject)) {
            $subject = '[系统通知]';
        }
    }
    
    
    $subject_encoded = '=?UTF-8?B?'.base64_encode($subject).'?=';
    
    
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    
    $from_name = !empty($conf['smtp_name']) ? $conf['smtp_name'] : '系统管理员';
    
    $headers .= "From: {$from_name} <{$conf['smtp_from']}>\r\n";
    
    $headers .= "Reply-To: {$conf['smtp_from']}\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    $headers .= "Sender: {$from_name} <{$conf['smtp_from']}>\r\n";
    
    
    $smtp_ssl = isset($conf['smtp_ssl']) ? $conf['smtp_ssl'] : 1;
    
    if($smtp_ssl == 1) {
        
        try {
            
            if(!function_exists('fsockopen')) {
                return '服务器不支持fsockopen函数，请联系空间提供商';
            }
            
            
            $prefix = '';
            $transport_protocol = 'tcp';
            
            
            if(strpos($conf['smtp_server'], 'mxhichina.com') !== false) {
                
                if($conf['smtp_port'] == 465) {
                    $prefix = 'ssl://';
                    $transport_protocol = 'ssl';
                } else if($conf['smtp_port'] == 587) {
                    
                    $transport_protocol = 'tls';
                }
            } else if($conf['smtp_port'] == 465) {
                
                $prefix = 'ssl://';
                $transport_protocol = 'ssl';
            }
            
            
            error_log('尝试连接SMTP服务器: ' . $prefix . $conf['smtp_server'] . ':' . $conf['smtp_port'] . ' 协议: ' . $transport_protocol);
            $socket = fsockopen($prefix . $conf['smtp_server'], $conf['smtp_port'], $errno, $errstr, 45); 
            
            if(!$socket) {
                return "无法连接到邮件服务器: $errstr ($errno)\n可能原因: 服务器防火墙阻止、SMTP服务未开启或配置错误";
            }
            
            stream_set_timeout($socket, 30);
            
            
            $response = fgets($socket, 1024);
            if(substr($response, 0, 3) != '220') {
                fclose($socket);
                return "连接服务器失败: $response";
            }
            
            
            fputs($socket, "EHLO localhost\r\n");
            
            $response = '';
            $status = 0;
            while($line = fgets($socket, 1024)) {
                $response .= $line;
                if(substr($line, 3, 1) == ' ') {
                    $status = substr($line, 0, 3);
                    break;
                }
            }
            if($status != '250') {
                fclose($socket);
                return "EHLO命令失败: $response";
            }
            
            
            if(($conf['smtp_port'] == 587 || $transport_protocol == 'tls') && strpos($response, 'STARTTLS') !== false) {
                error_log('尝试发送STARTTLS命令以启用加密连接');
                fputs($socket, "STARTTLS\r\n");
                $response = fgets($socket, 1024);
                if(substr($response, 0, 3) != '220') {
                    fclose($socket);
                    return "STARTTLS命令失败: $response";
                }
                
                
                if(!function_exists('stream_socket_enable_crypto')) {
                    fclose($socket);
                    return '服务器不支持stream_socket_enable_crypto函数，无法建立TLS连接';
                }
                
                
                $crypto_methods = array(
                    STREAM_CRYPTO_METHOD_TLS_CLIENT,
                    STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
                    STREAM_CRYPTO_METHOD_SSLv23_CLIENT
                );
                
                $crypto_result = false;
                foreach($crypto_methods as $method) {
                    error_log('尝试使用加密方法: ' . $method);
                    $crypto_result = @stream_socket_enable_crypto($socket, true, $method);
                    if($crypto_result) {
                        error_log('TLS加密连接成功建立');
                        break;
                    }
                }
                
                if(!$crypto_result) {
                    fclose($socket);
                    return '无法建立TLS加密连接（尝试了多种加密方法）';
                }
                
                
                fputs($socket, "EHLO localhost\r\n");
                
                $response = '';
                $status = 0;
                while($line = fgets($socket, 1024)) {
                    $response .= $line;
                    if(substr($line, 3, 1) == ' ') {
                        $status = substr($line, 0, 3);
                        break;
                    }
                }
                if($status != '250') {
                    fclose($socket);
                    return "TLS加密后EHLO命令失败: $response";
                }
            }
            
            
            fputs($socket, "AUTH LOGIN\r\n");
            $response = fgets($socket, 1024);
            if(substr($response, 0, 3) != '334') {
                fclose($socket);
                return "认证请求失败: $response\n可能原因: SMTP服务器不支持LOGIN认证方式";
            }
            
            
            fputs($socket, base64_encode($conf['smtp_user']) . "\r\n");
            $response = fgets($socket, 1024);
            if(substr($response, 0, 3) != '334') {
                fclose($socket);
                return "用户名认证失败: $response";
            }
            
            
            fputs($socket, base64_encode($conf['smtp_pass']) . "\r\n");
            $response = fgets($socket, 1024);
            if(substr($response, 0, 3) != '235') {
                fclose($socket);
                return "密码认证失败: $response\n可能原因: 用户名或密码错误，或未开启SMTP服务";
            }
            
            
            fputs($socket, "MAIL FROM: <{$conf['smtp_from']}>\r\n");
            $response = fgets($socket, 1024);
            if(substr($response, 0, 3) != '250') {
                fclose($socket);
                return "设置发件人失败: $response";
            }
            
            
            fputs($socket, "RCPT TO: <$to>\r\n");
            $response = fgets($socket, 1024);
            if(substr($response, 0, 3) != '250' && substr($response, 0, 3) != '251') {
                fclose($socket);
                return "设置收件人失败: $response\n可能原因: 收件人邮箱不存在或被服务器拒绝";
            }
            
            
            fputs($socket, "DATA\r\n");
            $response = fgets($socket, 1024);
            if(substr($response, 0, 3) != '354') {
                fclose($socket);
                return "开始数据传输失败: $response";
            }
            
            
            
            
            $headers .= "Subject: $subject_encoded\r\n";
            
            
            $email_content = rtrim($headers, "\r\n") . "\r\n\r\n" . $message;
            
            
            stream_set_blocking($socket, true);
            
            
            stream_set_write_buffer($socket, 0);
            stream_set_read_buffer($socket, 0);
            
            
            $chunk_size = (strpos($conf['smtp_server'], 'mxhichina.com') !== false) ? 1024 : 2048;
            $delay_us = (strpos($conf['smtp_server'], 'mxhichina.com') !== false) ? 20000 : 10000; 
            
            error_log('开始发送邮件内容 - 分块大小: ' . $chunk_size . ' 字节, 每块延迟: ' . ($delay_us/1000) . 'ms');
            $chunks = str_split($email_content, $chunk_size);
            $total_chunks = count($chunks);
            foreach ($chunks as $index => $chunk) {
                $written = fwrite($socket, $chunk);
                
                if($written !== false) {
                    error_log('已发送块 ' . ($index+1) . '/' . $total_chunks . ': ' . $written . ' 字节');
                } else {
                    error_log('发送块 ' . ($index+1) . '/' . $total_chunks . ' 失败');
                }
                
                usleep($delay_us);
            }
            
            
            error_log('发送邮件结束标志');
            $end_marker = "\r\n.\r\n";
            fwrite($socket, $end_marker);
            usleep($delay_us); 
            
            
            $response = '';
            $attempts = 0;
            $max_attempts = 5; 
            $total_response = '';
            
            while (empty($response) && $attempts < $max_attempts) {
                $attempts++;
                
                $timeout = 5 + ($attempts * 2); 
                stream_set_timeout($socket, $timeout);
                $response = fgets($socket, 4096); 
                
                if (!empty($response)) {
                    $total_response .= $response;
                }
                
                
                if (empty($response)) {
                    usleep(50000 * $attempts); 
                }
            }
            
            
            if(empty($total_response)) {
                
                error_log('SMTP连接详情 - 服务器: ' . $conf['smtp_server'] . ', 端口: ' . $conf['smtp_port'] . ', SSL: ' . ($conf['smtp_ssl'] ? '是' : '否') . ', 连接状态: 已建立但无响应');
                
                
                $socket_info = stream_get_meta_data($socket);
                $timed_out = $socket_info['timed_out'] ? '是' : '否';
                error_log('Socket状态 - 超时: ' . $timed_out . ', 阻塞: ' . ($socket_info['blocked'] ? '是' : '否'));
                
                fclose($socket);
                
                $ssl_status = $conf['smtp_ssl'] ? '开启' : '关闭';
                return "发送邮件内容失败: 未收到服务器响应\n可能原因: 服务器连接中断、网络超时或配置问题\n详细信息: SMTP服务器[" . $conf['smtp_server'] . ":" . $conf['smtp_port'] . "], SSL[$ssl_status]\n建议: 1) 检查SMTP服务器稳定性和网络连接 2) 确认服务器防火墙未阻止连接 3) 尝试更换SMTP端口(如465、587、25) 4) 检查服务器空间商是否限制了SMTP连接";
            }
            if(substr($total_response, 0, 3) != '250') {
                fclose($socket);
                
                return "发送邮件内容失败: " . trim($total_response) . "\n可能原因: 邮件内容格式错误、服务器限制或配置问题\n详细信息: 服务器响应代码[" . $total_response . "]\n建议: 1) 检查邮件内容是否合规 2) 确认未超过服务器邮件大小限制 3) 验证发件人域名是否配置正确 4) 检查是否需要设置DKIM/SPF记录";
            }
            
            
            fputs($socket, "QUIT\r\n");
            $response = fgets($socket, 1024);
            
            
            fclose($socket);
            
            
            add_email_log($to, $subject, 1);
            return true;
        } catch (Exception $e) {
            
            error_log('邮件发送异常: ' . $e->getMessage());
            $error_msg = '邮件发送过程中发生异常: ' . $e->getMessage();
            add_email_log($to, $subject, 0, $error_msg);
            return $error_msg;
        } catch (Error $e) {
            
            error_log('邮件发送错误: ' . $e->getMessage());
            $error_msg = '邮件发送过程中发生错误: ' . $e->getMessage();
            add_email_log($to, $subject, 0, $error_msg);
            return $error_msg;
        }
    } else {
        
        try {
            
            if(!function_exists('mail')) {
                $error_msg = '服务器不支持mail函数';
                add_email_log($to, $subject, 0, $error_msg);
                return $error_msg;
            }
            
            $result = mail($to, $subject, $message, $headers);
            if($result === false) {
                $error_msg = 'mail函数执行失败，请检查服务器邮件配置';
                add_email_log($to, $subject, 0, $error_msg);
                return $error_msg;
            }
            
            add_email_log($to, $subject, 1);
            return true;
        } catch (Exception $e) {
            $error_msg = '普通邮件发送失败: ' . $e->getMessage();
            add_email_log($to, $subject, 0, $error_msg);
            return $error_msg;
        }
    }
}


function generate_verification_code($length = 6) {
    $chars = '0123456789';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $code;
}


function get_email_template($type, $data = array()) {
    global $conf;
    
    $site_name = $conf['name'];
    $site_url = $conf['url'];
    $admin_email = $conf['email'];
    
    
    $styles = "
        body { font-family: 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5; margin: 0; padding: 0; }
        .container { max-width: 600px; margin: 20px auto; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); overflow: hidden; }
        .header { background-color: #3498db; color: #fff; padding: 20px; text-align: center; }
        .header h1 { margin: 0; font-size: 24px; }
        .content { padding: 30px; }
        .content p { margin: 15px 0; }
        .verification-code { font-size: 32px; font-weight: bold; color: #e74c3c; text-align: center; margin: 20px 0; padding: 15px; background-color: #f9f9f9; border-radius: 4px; letter-spacing: 5px; }
        .note { font-size: 14px; color: #777; margin-top: 20px; padding-top: 20px; border-top: 1px solid #eee; }
        .footer { background-color: #f8f9fa; padding: 20px; text-align: center; font-size: 14px; color: #777; border-top: 1px solid #eee; }
        .footer a { color: #3498db; text-decoration: none; }
        .bottom-right { margin: 30px 0 0 0; text-align: center; /* 显示在内容下方居中 */ }
        .bottom-right-content { text-align: center; /* 确保网站名称和时间居中显示 */ }
        .system-note { display: block; margin-top: 10px; font-size: 12px; color: #999; text-align: center; }
        .bottom-center { text-align: right; margin: 20px 0; padding-right: 30px; }
        .site-name { font-weight: bold; color: #3498db; }
        .site-name-black { font-weight: bold; color: #000; }
        .send-time { font-size: 12px; color: #999; }
    ";
    
    switch ($type) {
        case 'verification':
            $subject = "[{$site_name}] 管理员密码重置验证码";
            $message = "<!DOCTYPE html>
            <html lang='zh-CN'>
            <head>
                <meta charset='UTF-8'>
                <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                <title>{$subject}</title>
                <style>{$styles}</style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h1>{$site_name}</h1>
                    </div>
                    <div class='content'>
                        <p>尊敬的管理员，</p>
                        <p>您正在尝试重置网站管理员密码，请使用以下验证码完成操作：</p>
                        <div class='verification-code'>{$data['code']}</div>
                        <p>验证码有效期为5分钟，请及时使用。</p>
                        <p>如果不是您本人操作，请忽略此邮件，或联系网站管理员。</p>
                        <div class='note'>
                            <p>如有疑问，请联系：{$admin_email}</p>
                        </div>
                    </div>
                    <div class='bottom-center'>
                        <p class='site-name-black'>{$site_name}</p>
                        <p class='send-time'>".date('Y-m-d H:i:s')."</p>
                    </div>
                    <div class='footer'>
                        <p><a href='{$site_url}' target='_blank' class='site-name'>{$site_name}</a></p>
                        <p class='system-note'>此邮件由系统自动发送，请勿回复</p>
                    </div>
                </div>
            </body>
            </html>";
            break;
            
        case 'account_login':
            $login_ip = isset($data['ip']) ? $data['ip'] : '未知IP';
            $login_time = date('Y-m-d H:i:s');
            $subject = "[{$site_name}] 管理员账户登录提醒";
            $message = "<!DOCTYPE html>
            <html lang='zh-CN'>
            <head>
                <meta charset='UTF-8'>
                <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                <title>{$subject}</title>
                <style>{$styles}</style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h1>{$site_name}</h1>
                    </div>
                    <div class='content'>
                        <p>尊敬的管理员，</p>
                        <p>您的账户于 {$login_time} 从IP地址 {$login_ip} 登录系统。</p>
                        <p>如果这不是您本人操作，请立即修改密码并检查系统安全。</p>
                        <div class='note'>
                            <p>如有疑问，请联系：{$admin_email}</p>
                        </div>
                    </div>
                    <div class='bottom-center'>
                        <p class='site-name-black'>{$site_name}</p>
                        <p class='send-time'>".date('Y-m-d H:i:s')."</p>
                    </div>
                    <div class='footer'>
                        <p><a href='{$site_url}' target='_blank' class='site-name'>{$site_name}</a></p>
                        <p class='system-note'>此邮件由系统自动发送，请勿回复</p>
                    </div>
                </div>
            </body>
            </html>";
            break;
            
        case 'test_success':
            $subject = "[{$site_name}] SMTP发信配置成功";
            $message = "<!DOCTYPE html>
            <html lang='zh-CN'>
            <head>
                <meta charset='UTF-8'>
                <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                <title>{$subject}</title>
                <style>{$styles}</style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h1>{$site_name}</h1>
                    </div>
                    <div class='content'>
                        <p>尊敬的管理员，</p>
                        <p>恭喜你，已成功完成SMTP发信配置！</p>
                        <p>这是一封测试邮件，说明您的邮件服务器设置正确，可以正常发送邮件。</p>
                        <div class='note'>
                        </div>
                    </div>
                    <div class='bottom-center'>
                        <p class='site-name-black'>{$site_name}</p>
                        <p class='send-time'>".date('Y-m-d H:i:s')."</p>
                    </div>
                    <div class='footer'>
                        <p><a href='{$site_url}' target='_blank' class='site-name'>{$site_name}</a></p>
                        <p class='system-note'>此邮件由系统自动发送，请勿回复</p>
                    </div>
                </div>
            </body>
            </html>";
            break;
            
        default:
            $subject = "[{$site_name}] 系统通知";
            $message = "<!DOCTYPE html>
            <html lang='zh-CN'>
            <head>
                <meta charset='UTF-8'>
                <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                <title>{$subject}</title>
                <style>{$styles}</style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h1>{$site_name}</h1>
                    </div>
                    <div class='content'>
                        <p>尊敬的管理员，</p>
                        <p>{$data['message']}</p>
                        <div class='note'>
                        </div>
                    </div>
                    <div class='bottom-center'>
                        <p class='site-name-black'>{$site_name}</p>
                        <p class='send-time'>".date('Y-m-d H:i:s')."</p>
                    </div>
                    <div class='footer'>
                        <p><a href='{$site_url}' target='_blank' class='site-name'>{$site_name}</a></p>
                        <p class='system-note'>此邮件由系统自动发送，请勿回复</p>
                    </div>
                </div>
            </body>
            </html>";
            break;
    }
    
    return array('subject' => $subject, 'message' => $message);
}


function send_verification_email($email, $code) {
    
    $template = get_email_template('verification', array('code' => $code));
    
    
    $result = send_email($email, $template['subject'], $template['message']);
    
    
    if ($result !== true) {
        error_log('邮件发送失败: ' . $result);
    }
    
    return $result;
}


function send_login_alert_email($email, $ip) {
    
    $template = get_email_template('account_login', array('ip' => $ip));
    
    
    return send_email($email, $template['subject'], $template['message']);
}


function send_system_notification_email($email, $message) {
    
    $template = get_email_template('default', array('message' => $message));
    
    
    return send_email($email, $template['subject'], $template['message']);
}


if (isset($_GET['act'])) {
    @header('Content-Type: application/json; charset=UTF-8');
    
    switch ($_GET['act']) {
        case 'send_code':
            $email = _post('email');
            
            if (empty($email)) {
                exit('{"code":-1,"msg":"邮箱不能为空！"}');
            }
            
            
            if ($email != $conf['email']) {
                exit('{"code":-2,"msg":"邮箱不正确！"}');
            }
            
            
            $code = generate_verification_code();
            
            
            $_SESSION['reset_code'] = $code;
            $_SESSION['reset_time'] = time();
            
            
            $result = send_verification_email($email, $code);
            
            if ($result === true) {
                exit('{"code":0,"msg":"验证码已发送至您的邮箱"}');
            } else {
                exit('{"code":-3,"msg":"邮件发送失败：' . $result . '"}');
            }
            break;
            
        case 'test_email':
            try {
                
                $smtp_server = _post('smtp_server');
                $smtp_port = _post('smtp_port');
                $smtp_from = _post('smtp_from');
                $smtp_user = _post('smtp_user');
                $smtp_pass = _post('smtp_pass');
                $smtp_ssl = _post('smtp_ssl') === '1' ? 1 : 0;
                
                $test_email = _post('test_email');
                
                
                if (empty($smtp_server)) {
                    exit('{"code":-1,"msg":"SMTP服务器不能为空"}');
                }
                
                if (empty($smtp_port) || !is_numeric($smtp_port) || $smtp_port < 1 || $smtp_port > 65535) {
                    exit('{"code":-2,"msg":"SMTP端口必须是有效的端口号(1-65535)"}');
                }
                
                if (empty($smtp_from) || !filter_var($smtp_from, FILTER_VALIDATE_EMAIL)) {
                    exit('{"code":-3,"msg":"发件人邮箱格式不正确"}');
                }
                
                if (empty($smtp_user)) {
                    exit('{"code":-4,"msg":"SMTP用户名不能为空"}');
                }
                
                if (empty($smtp_pass)) {
                    exit('{"code":-5,"msg":"SMTP密码不能为空"}');
                }
                
                
                if (!empty($test_email) && !filter_var($test_email, FILTER_VALIDATE_EMAIL)) {
                    exit('{"code":-6,"msg":"测试邮箱格式不正确"}');
                }
                
                
                $original_conf = $conf;
                
                
                $conf['smtp_server'] = $smtp_server;
                $conf['smtp_port'] = $smtp_port;
                $conf['smtp_from'] = $smtp_from;
                $conf['smtp_user'] = $smtp_user;
                $conf['smtp_pass'] = $smtp_pass;
                $conf['smtp_ssl'] = $smtp_ssl;
                
                
                
                $test_template = get_email_template('test_success');
                
                
                $recipient_email = !empty($test_email) ? $test_email : $smtp_from;
                
                
                try {
                    $result = send_email($recipient_email, $test_template['subject'], $test_template['message']);
                } catch (Exception $se) {
                    $result = $se->getMessage();
                }
                
                
                $conf = $original_conf;
                
                if ($result === true) {
                    exit('{"code":0,"msg":"测试邮件发送成功，请注意查收"}');
                } else {
                    
                    error_log('邮件测试失败 - 服务器: ' . $smtp_server . ', 端口: ' . $smtp_port . ', 错误: ' . $result);
                    
                    
                    $response = array(
                        'code' => -7,
                        'msg' => '邮件发送失败：' . $result
                    );
                    exit(json_encode($response, JSON_UNESCAPED_UNICODE));
                }
            } catch (Exception $e) {
                
                error_log('邮件测试异常: ' . $e->getMessage());
                
                
                $response = array(
                    'code' => -99,
                    'msg' => '测试过程中发生异常：' . $e->getMessage()
                );
                exit(json_encode($response, JSON_UNESCAPED_UNICODE));
            }
            break;
            
        default:
            exit('{"code":-4,"msg":"未知操作"}');
    }
}
?>